define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {

    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'goods/index' + location.search,
                    add_url: 'goods/add',
                    edit_url: 'goods/edit',
                    del_url: 'goods/del',
                    multi_url: 'goods/multi',
                    import_url: 'goods/import',
                    table: 'goods',
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'weigh',
                fixedColumns: true,
                fixedRightNumber: 1,
                search: false,         //搜索框
                columns: [
                    [
                        { checkbox: true },
                        { field: 'id', title: __('Id'), operate: false },
                        // {field: 'one_id', title: __('One_id')},
                        // {field: 'two_id', title: __('Two_id')},
                        { field: 'typeone.name', title: __('一级分类'), operate: 'LIKE', table: table, class: 'autocontent', formatter: Table.api.formatter.search },
                        { field: 'typetwo.name', title: __('二级分类'), operate: 'LIKE', table: table, class: 'autocontent', formatter: Table.api.formatter.search },
                        { field: 'brand.name', title: __('品牌'), operate: 'LIKE', table: table, class: 'autocontent', formatter: Table.api.formatter.content },
                        { field: 'goods_image', title: __('Goods_image'), operate: false, events: Table.api.events.image, formatter: Table.api.formatter.image },
                        { field: 'name', title: __('Name'), operate: 'LIKE', table: table, class: 'autocontent', formatter: Table.api.formatter.content },
                        // { field: 'sales', title: __('Sales'), operate: false, table: table, class: 'autocontent', formatter: Table.api.formatter.content },
                        // {field: 'brand_id', title: __('Brand_id')},
                        { field: 'orgin', title: __('Orgin'), operate: 'LIKE', table: table, class: 'autocontent', formatter: Table.api.formatter.content },
                        { field: 'vein', title: __('Vein'), operate: 'LIKE', table: table, class: 'autocontent', formatter: Table.api.formatter.content },
                        { field: 'material', title: __('Material'), operate: 'LIKE', table: table, class: 'autocontent', formatter: Table.api.formatter.content },
                        // { field: 'size', title: __('Size'), operate: 'LIKE', table: table, class: 'autocontent', formatter: Table.api.formatter.content },
                        // {field: 'content', title: __('Content')},
                        { field: 'recommend', title: __('Recommend'), searchList: { "1": __('Recommend 1'), "2": __('Recommend 2') }, formatter: Table.api.formatter.normal },
                        { field: 'status', title: __('Status'), searchList: { "1": __('Status 1'), "2": __('Status 2') }, formatter: Table.api.formatter.status },
                        { field: 'createtime', title: __('Createtime'), operate: 'RANGE', addclass: 'datetimerange', autocomplete: false, formatter: Table.api.formatter.datetime },
                        { field: 'updatetime', title: __('Updatetime'), operate: 'RANGE', addclass: 'datetimerange', autocomplete: false, formatter: Table.api.formatter.datetime },
                        { field: 'weigh', title: __('Weigh'), operate: false },
                        { field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, formatter: Table.api.formatter.operate }
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        add: function () {
            Controller.api.bindevent();
            this.initLevelDependency();
            Template.helper("Fast", Fast);
            $(document).ready(function () {
                // 颜色选择器变化时更新文本输入框
                $(document).on('change', '.color-picker', function () {
                    var colorValue = $(this).val();
                    $(this).closest('.input-group').find('.color-value').val(colorValue);
                });

                // 文本输入框变化时验证格式并更新颜色选择器
                $(document).on('change', '.color-value', function () {
                    var val = $(this).val();
                    if (!val) return;

                    // 如果不是以#开头，自动添加
                    if (!val.startsWith('#')) {
                        val = '#' + val;
                        $(this).val(val);
                    }

                    // 验证是否为有效的十六进制颜色
                    if (/^#[0-9A-F]{6}$/i.test(val)) {
                        $(this).closest('.input-group').find('.color-picker').val(val);
                    } else {
                        // 无效颜色提示
                        Toastr.error('请输入有效的十六进制颜色值（如#RRGGBB）');
                    }
                });

                // 初始化时确保颜色值格式正确
                $('.color-value').each(function () {
                    var val = $(this).val();
                    if (val && !val.startsWith('#')) {
                        $(this).val('#' + val);
                    }
                });
            });
            $(document).on("fa.event.appendfieldlist", "#second-table .btn-append", function (e, obj) {
                //绑定上传组件
                Form.events.faupload(obj);

                //上传成功回调事件，变更按钮的背景
                $(".upload-image", obj).data("upload-success", function (data) {
                    $(this).css("background-image", "url('" + Fast.api.cdnurl(data.url) + "')");
                })
            });
        },
        edit: function () {
            Controller.api.bindevent();
            this.initLevelDependency();
            this.initEditPage();
            Template.helper("Fast", Fast);
            $(document).ready(function () {
                // 颜色选择器变化时更新文本输入框
                $(document).on('change', '.color-picker', function () {
                    var colorValue = $(this).val();
                    $(this).closest('.input-group').find('.color-value').val(colorValue);
                });

                // 文本输入框变化时验证格式并更新颜色选择器
                $(document).on('change', '.color-value', function () {
                    var val = $(this).val();
                    if (!val) return;

                    // 如果不是以#开头，自动添加
                    if (!val.startsWith('#')) {
                        val = '#' + val;
                        $(this).val(val);
                    }

                    // 验证是否为有效的十六进制颜色
                    if (/^#[0-9A-F]{6}$/i.test(val)) {
                        $(this).closest('.input-group').find('.color-picker').val(val);
                    } else {
                        // 无效颜色提示
                        Toastr.error('请输入有效的十六进制颜色值（如#RRGGBB）');
                    }
                });

                // 初始化时确保颜色值格式正确
                $('.color-value').each(function () {
                    var val = $(this).val();
                    if (val && !val.startsWith('#')) {
                        $(this).val('#' + val);
                    }
                });
            });
            $(document).on("fa.event.appendfieldlist", "#second-table .btn-append", function (e, obj) {
                //绑定上传组件
                Form.events.faupload(obj);

                //上传成功回调事件，变更按钮的背景
                $(".upload-image", obj).data("upload-success", function (data) {
                    $(this).css("background-image", "url('" + Fast.api.cdnurl(data.url) + "')");
                })
            });
        },
        // 新增方法：初始化层级联动
        initLevelDependency: function () {
            $("#c-one_id").on('change', function () {
                var one_id = $("input.sp_hidden[name='row[one_id]']").val();
                var $pidSelect = $("#c-two_id");
                // 先显示加载状态
                $pidSelect.html('<option value="">加载中...</option>').selectpicker('refresh');
                // 加载二级分类
                $.ajax({
                    url: 'Typetwo/selectpage',
                    dataType: 'json',
                    data: { pid: one_id },
                    success: function (res) {
                        var options = '<option value="0">请选择二级分类</option>';
                        $.each(res.list, function (i, item) {
                            options += '<option value="' + item.id + '">' + item.name + '</option>';
                        });
                        $pidSelect.html(options).selectpicker('refresh');
                    }
                });
            });

            // 添加页面加载后触发一次change事件
            $("#c-level").trigger('change');
        },

        // 新增方法：编辑页面特殊处理
        initEditPage: function () {
            // 如果是编辑页面，设置已选中的父级
            var currentPid =$("input.sp_hidden[name='row[one_id]']").val();
            if (currentPid && currentPid != 0) {
                // 延迟设置确保选项已加载
                setTimeout(function () {
                    $("#c-two_id").val(currentPid).selectpicker('refresh');
                }, 300);
            }
        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
            }
        }
    };
    return Controller;
});
